package com.qianfeng.smartplatform.security.handler;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.dto.R;
import com.qianfeng.smartplatform.pojo.Menu;
import com.qianfeng.smartplatform.pojo.Role;
import com.qianfeng.smartplatform.security.BaseUser;
import com.qianfeng.smartplatform.service.MenuService;
import com.qianfeng.smartplatform.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2021/12/21/下午9:27
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    private RoleService roleService;


    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //  super.onAuthenticationSuccess(request, response, authentication);
        BaseUser user = ((BaseUser) authentication.getPrincipal());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<Role> roleList = roleService.findRolesByUserId(user.getId());
        roleList.forEach(role -> {
            List<Menu> menuList = menuService.findAllMenusByRoleId(role.getRoleId());
            role.setMenuList(menuList);
            //添加角色
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + role.getRoleName());
            //给权限中添加角色
            grantedAuthorities.add(simpleGrantedAuthority);
            //遍历所有权限,给用户添加
            List<SimpleGrantedAuthority> authorityList = menuList.stream()
                    //先获取到所有的权限字符串,通过map转换成字符串
                    .map(Menu::getPerms)
                    //过滤掉空的数据
                    .filter(perms -> !ObjectUtils.isEmpty(perms))
                    //用不为空的权限字符串生成SimpleGrantedAuthority权限对象
                    .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            //添加所有权限
            grantedAuthorities.addAll(authorityList);
        });
        //设置权限
        user.setRoleList(roleList);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), grantedAuthorities));
        //  //发布用户登录成功的操作,更新用户的登录时间,此处需要设置登录ip和地区
//        response.sendRedirect("/index.html");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(R.setOK(null)));
    }
}
